package com.edu.backend.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;

import com.edu.backend.entity.Admin;
import com.edu.backend.entity.AdminDTO;
import com.edu.backend.entity.User;
import com.edu.backend.service.AdminService;
import com.edu.backend.utils.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;


@RestController
public class AdminController {
    @Resource
    AdminService userService;
    @PostMapping("/login")
    public R login(@RequestBody Admin admin) {
        String token = userService.login(admin);
        return R.ok().data("token", token);
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public R info(String token) {
        if (token == null) R.ok().data("user", null);
        AdminDTO user = userService.getAdminInfo(token);
        System.out.println(user);
        return R.ok().data("user", user);
    }

    @PutMapping("/updateAdmin")
    public R updateAdmin(@RequestBody Admin admin){
        System.out.println(admin.toString());
        Boolean result=userService.updateAdmin(admin);
        if(result){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @ApiOperation("登出")
    @GetMapping("logout")
    public R logout(@RequestParam String token) {
        System.out.println(token);
        userService.logout(token);
        return R.ok().code(5000);
    }

    @PostMapping("/upload")
    public R uploadFile(@RequestParam MultipartFile file,@RequestParam String id){
        String filename = file.getOriginalFilename();
        String suffixName = filename.substring(filename.lastIndexOf("."));  // 后缀名
        String filePath = "D:\\桌面\\qndxxz-master\\src\\assets\\img\\"; // 上传后的路径
        filename = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + filename);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        userService.updateAvatarById(filename,Integer.valueOf(id));
        System.out.println(filename);
        return R.ok().data("filename",filename);
    }
    @GetMapping("/getAdmin/{id}")
    public R getAdmin(@PathVariable(value = "id") String id){
        System.out.println("id:"+id);
        Admin admin=userService.getAdmin(Integer.valueOf(id));
        String jsonStr = JSON.toJSONString(admin, SerializerFeature.WriteDateUseDateFormat);
        Map<String, Object> map = JSON.parseObject(jsonStr, new TypeReference<Map<String, Object>>() {});
        return R.ok().data(map);
    }
}
